package controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import common.CommException;
import domain.User;
import Service.UserService;
/**
 * 处理修改密码的请求
 * @author cqyhm
 *
 */
@WebServlet(urlPatterns= {"/changepwd.do"})
public class ChangepwdServlet extends HttpServlet{

	private static final long serialVersionUID = 1864179080408636925L;
	private Logger logger=LoggerFactory.getLogger(getClass());
	private UserService userService=new UserService();
	/**
	 * 处理get方法发送过来的请求
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	/**
	 * 处理post方法发送过来的请求
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		logger.info("changePwd.dopost");
		try {
			//1.接收前台传递过来的参数
			String usercode=req.getParameter("usercode");
			String password=req.getParameter("password");
			String newPassword=req.getParameter("newpassword");
			String confirm=req.getParameter("confirm");
			//2.参数类型转换
			//3.参数合法性校验
			if(usercode==null||usercode.trim().length()<=0) {
				throw new CommException("必须指定要修改密码的账号");
			}
			if(password==null||password.trim().length()<=0) {
				throw new CommException("必须指定原始密码");
			}
			if(newPassword==null||newPassword.trim().length()<=0) {
				throw new CommException("必须指定新密码");
			}
			if(confirm==null||confirm.trim().length()<=0) {
				throw new CommException("必须重新输入新密码");
			}
			if(!confirm.equals(newPassword)) {
				throw new CommException("两次输入的新密码必须相等");
			}
			//4.参数封装为对象
			User user=new User();
			user.setUsercode(usercode); //账号
			user.setPassword(password); //旧密码
			user.setNewPassword(newPassword);//新密码
			//5.调用业务方法
			userService.changePwd(user);
			//6.转发或重定向(可传递数据给页面)
			resp.sendRedirect(req.getContextPath()+"/index.jsp");
			logger.info("改变密码成功");
		} catch (Exception e) {
			e.printStackTrace();
			req.setAttribute("error", e.getMessage());
			req.getRequestDispatcher("/changepwd.jsp").forward(req, resp);
			logger.error("改变密码失败:{}",e.getMessage());
		}
	}

}
